import React from 'react';
import { BarChart3, Clock, Calendar, TrendingUp } from 'lucide-react';
import { FishEvent, DateFilter } from '../types';
import { fishCategories } from '../data/categories';
import { DateUtil } from '../utils/storage';

interface StatisticsProps {
  events: FishEvent[];
  dateFilter: DateFilter;
  onDateFilterChange: (filter: DateFilter) => void;
}

const Statistics: React.FC<StatisticsProps> = ({
  events,
  dateFilter,
  onDateFilterChange
}) => {
  const filteredEvents = events.filter(event => {
    switch (dateFilter) {
      case 'today':
        return DateUtil.isToday(event.timestamp);
      case 'week':
        return DateUtil.isThisWeek(event.timestamp);
      case 'month':
        return DateUtil.isThisMonth(event.timestamp);
      default:
        return true;
    }
  });

  // 统计数据计算
  const totalEvents = filteredEvents.length;
  const totalDuration = filteredEvents.reduce((sum, event) => sum + event.duration, 0);
  const avgDuration = totalEvents > 0 ? Math.round(totalDuration / totalEvents) : 0;

  // 按类型统计
  const categoryStats = fishCategories.map(category => {
    const categoryEvents = filteredEvents.filter(event => event.type === category.id);
    const duration = categoryEvents.reduce((sum, event) => sum + event.duration, 0);
    return {
      ...category,
      count: categoryEvents.length,
      duration,
      percentage: totalEvents > 0 ? Math.round((categoryEvents.length / totalEvents) * 100) : 0
    };
  }).filter(stat => stat.count > 0).sort((a, b) => b.duration - a.duration);

  // 每日统计（最近7天）
  const last7Days = Array.from({ length: 7 }, (_, i) => {
    const date = new Date();
    date.setDate(date.getDate() - i);
    return date;
  }).reverse();

  const dailyStats = last7Days.map(date => {
    const dayEvents = events.filter(event => {
      const eventDate = new Date(event.timestamp);
      return eventDate.toDateString() === date.toDateString();
    });
    
    return {
      date: date.toLocaleDateString('zh-CN', { month: 'numeric', day: 'numeric' }),
      count: dayEvents.length,
      duration: dayEvents.reduce((sum, event) => sum + event.duration, 0)
    };
  });

  const maxDailyDuration = Math.max(...dailyStats.map(stat => stat.duration), 1);

  const filterButtons = [
    { key: 'today' as DateFilter, label: '今天' },
    { key: 'week' as DateFilter, label: '本周' },
    { key: 'month' as DateFilter, label: '本月' },
    { key: 'all' as DateFilter, label: '全部' }
  ];

  return (
    <div className="space-y-6">
      {/* 时间筛选 */}
      <div className="bg-white rounded-lg shadow-md p-6 animate-slide-up hover:shadow-lg transition-shadow duration-300">
        <h2 className="text-xl font-bold text-gray-800 mb-4 flex items-center gap-2">
          <BarChart3 className="h-5 w-5 animate-bounce-gentle" />
          数据统计
        </h2>
        
        <div className="flex gap-2 mb-4">
          {filterButtons.map((button, index) => (
            <button
              key={button.key}
              onClick={() => onDateFilterChange(button.key)}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 transform hover:scale-105 active:scale-95 animate-fade-in-up ${
                dateFilter === button.key
                  ? 'bg-blue-500 text-white shadow-md animate-pulse-gentle'
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200 hover:shadow-md'
              }`}
              style={{ animationDelay: `${index * 100}ms` }}
            >
              {button.label}
            </button>
          ))}
        </div>

        {/* 总览数据 */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="bg-gradient-to-r from-blue-500 to-purple-500 text-white p-4 rounded-lg animate-fade-in-up hover:scale-105 transition-transform duration-300 hover:shadow-lg">
            <div className="flex items-center gap-2 mb-2">
              <Calendar className="h-5 w-5 animate-bounce-gentle" />
              <span className="font-medium">摸鱼次数</span>
            </div>
            <div className="text-2xl font-bold animate-count-up">{totalEvents}</div>
          </div>
          
          <div className="bg-gradient-to-r from-green-500 to-teal-500 text-white p-4 rounded-lg animate-fade-in-up animation-delay-200 hover:scale-105 transition-transform duration-300 hover:shadow-lg">
            <div className="flex items-center gap-2 mb-2">
              <Clock className="h-5 w-5 animate-spin-slow" />
              <span className="font-medium">总时长</span>
            </div>
            <div className="text-2xl font-bold animate-count-up">{DateUtil.formatDuration(totalDuration)}</div>
          </div>
          
          <div className="bg-gradient-to-r from-orange-500 to-red-500 text-white p-4 rounded-lg animate-fade-in-up animation-delay-400 hover:scale-105 transition-transform duration-300 hover:shadow-lg">
            <div className="flex items-center gap-2 mb-2">
              <TrendingUp className="h-5 w-5 animate-bounce-gentle" />
              <span className="font-medium">平均时长</span>
            </div>
            <div className="text-2xl font-bold animate-count-up">{DateUtil.formatDuration(avgDuration)}</div>
          </div>
        </div>
      </div>

      {/* 类型统计 */}
      {categoryStats.length > 0 && (
        <div className="bg-white rounded-lg shadow-md p-6 animate-slide-up animation-delay-200 hover:shadow-lg transition-shadow duration-300">
          <h3 className="text-lg font-semibold text-gray-800 mb-4 animate-fade-in-up">按类型统计</h3>
          <div className="space-y-4">
            {categoryStats.map((stat, index) => (
              <div key={stat.id} className="animate-fade-in-up" style={{ animationDelay: `${index * 100}ms` }}>
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center gap-2">
                    <span className="text-xl animate-bounce-gentle">{stat.icon}</span>
                    <span className="font-medium hover:text-blue-600 transition-colors duration-200">{stat.name}</span>
                    <span className="text-sm text-gray-600">({stat.count}次)</span>
                  </div>
                  <div className="text-right">
                    <div className="font-semibold">{DateUtil.formatDuration(stat.duration)}</div>
                    <div className="text-sm text-gray-600">{stat.percentage}%</div>
                  </div>
                </div>
                <div className="bg-gray-200 rounded-full h-2 overflow-hidden">
                  <div
                    className={`${stat.color} h-2 rounded-full transition-all duration-1000 ease-out animate-expand-width`}
                    style={{ width: `${stat.percentage}%` }}
                  />
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 每日趋势 */}
      <div className="bg-white rounded-lg shadow-md p-6 animate-slide-up animation-delay-400 hover:shadow-lg transition-shadow duration-300">
        <h3 className="text-lg font-semibold text-gray-800 mb-4 animate-fade-in-up">最近7天趋势</h3>
        <div className="flex items-end gap-2 h-32 animate-fade-in">
          {dailyStats.map((stat, index) => (
            <div key={stat.date} className="flex-1 flex flex-col items-center animate-slide-up" style={{ animationDelay: `${index * 100}ms` }}>
              <div className="w-full bg-gray-200 rounded-t flex-1 flex items-end hover:bg-gray-300 transition-colors duration-200">
                <div
                  className="w-full bg-gradient-to-t from-blue-400 to-blue-500 rounded-t transition-all duration-1000 ease-out animate-grow-height hover:from-blue-500 hover:to-blue-600"
                  style={{ 
                    height: `${stat.duration > 0 ? Math.max((stat.duration / maxDailyDuration) * 100, 5) : 0}%` 
                  }}
                />
              </div>
              <div className="text-xs text-center mt-2 hover:text-blue-600 transition-colors duration-200">
                <div className="font-medium">{stat.date}</div>
                <div className="text-gray-600">{stat.count}次</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default Statistics;